package rsexplorer.rstree;

import rsexplorer.tree.SortableTreeNode;
import rsexplorer.utils.FieldFilter;
import java.lang.reflect.Field;
import javax.swing.tree.MutableTreeNode;


public class FieldFilterTreeNode extends SortableTreeNode{

    protected FieldFilter filter;

    public FieldFilterTreeNode(Object userObject) {
        this(userObject, null);
    }
    public FieldFilterTreeNode(Object userObject, FieldFilter filter) {
        this(userObject, true, filter);
    }
    public FieldFilterTreeNode(Object userObject, boolean sortChildren, FieldFilter filter) {
        super(userObject, sortChildren);
        this.filter = filter;
    }

    /**
     * Attachs a field filter to this node.
     * @param filter the new filter.
     */
    public void attachFilter(FieldFilter filter) {
        this.filter = filter;
    }

    /**
     * Detaches the current field filter.
     */
    public void detachFilter() {
        this.filter = null;
    }

    /**
     * Gets the current filter.
     * @return the current filter.
     */
    public FieldFilter getFilter() {
        return filter;
    }

    /**
     * See {@link FieldFilter#shouldFilterPrimitive(java.lang.Object)}
     */
    protected boolean shouldFilterPrimitive(Object object) {
        return filter != null && filter.shouldFilterPrimitive(object);
    }

    /**
     * @see FieldFilter#shouldFilterObject(java.lang.Object)
     */
    protected boolean shouldFilterObject(Object object) {
        return filter != null && filter.shouldFilterObject(object);
    }

    /**
     * @see FieldFilter#shouldFilterArray(java.lang.Object)
     */
    protected boolean shouldFilterArray(Object object) {
        return filter != null && filter.shouldFilterArray(object);
    }

    /**
     * @see FieldFilter#shouldFilterField(Field field)
     */
    protected boolean shouldFilterField(Field field) {
        return filter != null && filter.shouldFilterField(field);
    }

    /**
     * Filters newChild based on it's class.
     * @see  SortableTreeNode#insert(MutableTreeNode newChild, int childIndex)}
     */
    @Override
    public void insert(MutableTreeNode newChild, int childIndex) {
        if (newChild instanceof ObjectFieldTreeNode || newChild instanceof ArrayFieldTreeNode) {
            if (newChild.getChildCount() > 0)
                super.insert(newChild, childIndex);
        } else super.insert(newChild, childIndex);
    }
}
